﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;

namespace AlbumDesigner.Helpers
{
    public class FilesHelper
    {
        public static long GetDirectorySize(string searchDirectory, bool includeSubDirectories = true)
        {
            if (!Directory.Exists(searchDirectory))
            {
                return 0;
            }

            var files = Directory.EnumerateFiles(searchDirectory);

            // get the size of all files in the current directory
            var currentSize = (from file in files let fileInfo = new FileInfo(file) select fileInfo.Length).Sum();

            var directories = Directory.EnumerateDirectories(searchDirectory);

            // get the size of all files in all subdirectories
            var subDirSize = (from directory in directories
                              select GetDirectorySize(directory)).Sum();

            if (includeSubDirectories)
            {
                currentSize += subDirSize;
            }

            return currentSize;
        }

        public static int GetDirectoryFilesCount(string searchDirectory)
        {
            if (!Directory.Exists(searchDirectory))
            {
                return 0;
            }

            var files = Directory.GetFiles(searchDirectory, "*.*", SearchOption.AllDirectories).Length;
            return files;
        }

        public static string BytesToMegaBytes(long value)
        {
            var kb = 1024.0;
            return (value / kb / kb).ToString("0.0");
        }

        public static string GetContentType(string fileUrl)
        {
            var extention = Path.GetExtension(fileUrl).ToUpper();
            
            switch(extention)
            {
                case ".GIF":
                    return "image/gif";

                case ".PNG":
                    return "image/png";

                case ".JPG":
                case ".JPEG":
                    return "image/jpeg";

                default:
                    return "unkonow";
            }
        }

        public static string MakeValidFileName(string name)
        {
            var builder = new StringBuilder();
            var invalid = System.IO.Path.GetInvalidFileNameChars();
            foreach (var cur in name)
            {
                if (!invalid.Contains(cur))
                {
                    builder.Append(cur);
                }
            }
            return builder.ToString();
        }

		static public bool FileExistsOnServer(string relativeUrl)
        {
            // Verify that image exists
            string fullPath = HttpContext.Current.Server.MapPath("~/") + relativeUrl;
            FileInfo fileInfo = new FileInfo(fullPath);
            return fileInfo.Exists;
        }

    }
}